package cn.tedu.boot42.controller;

import cn.tedu.boot42.entity.User;
import cn.tedu.boot42.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/check")
    public String check(String username){
        int i = mapper.findUserByUsername(username);
        System.out.println(this.toString() + i);
        if ( i == 1) {
            return "该用户名已存在!";
        }
        return "该用户名可用!";
    }
    @RequestMapping("/reg")
    public int reg(User user){
        int info = mapper.findUserByUsername(user.getUsername());
        if (info == 1) {
            return 0;
        }
        int i = mapper.insertUser(user);
        if ( i == 1) {
            return 1;
        }
        return 0;
    }
    @RequestMapping("/login")
    public int reg(String username, String password){
        int u = mapper.findUserByUsername(username);
        if(u == 0){
            return 2; //用户名已存在
        }
        int i = mapper.findUserByUP(username,password);
        if ( i == 1) {
            return 1; //登录成功
        }
        return 0; //用户名或密码错误
    }

    /**
     * 获取所有用户
     * @return 返回User的list
     */
    @RequestMapping("/userlist")
    public List<User> UserList(){
        List<User> users = mapper.findAll();
        return users;
    }

    @RequestMapping("/update")
    public int UpdateUser(User user){
        int i = mapper.updateUserById(user);
        if (i == 1){
            return 1;
        }
        return 0;
    }
    @RequestMapping("/delete")
    public int DeleteUser(Integer id){
        System.out.println(id);
        int i = mapper.deleteUserById(id);
        if (i == 1){
            return 1;
        }
        return 0;
    }

}
